<template>
  <el-container class="exam">
    <el-header>
      <h3>{{ examInfo.name }}</h3>
      <span v-if="type == 'readonly'">成绩：{{score}}，总分 {{totalScore}}</span>
      <div>
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="small"
          @click="exit"
        >退出
        </el-button
        >
      </div>
    </el-header>
    <el-main v-loading="loading" ref="problemsBody">
      <!-- 左侧答题卡区域 -->
      <el-card class="answer-sheet">
        <div slot="header" class="clearfix">
          <span>答题卡</span>
        </div>
        <div class="body">
          <div
            v-for="(item, index) in Object.keys(afterProblem)"
            :key="index"
            v-show="afterProblem[item].length > 0"
          >
            <p>{{ item }}（共{{ afterProblem[item].length }}题）</p>
            <el-button
              plain
              size="mini"
              v-for="i in afterProblem[item].length"
              :key="i"
              :type="problemState(item, i)"
              :class="{ isFirst: i % 5 == 1 ? true : false }"
              @click="roll(item, i)"
            >{{ i }}
            </el-button
            >
          </div>
        </div>
      </el-card>

      <!-- 右侧计时器 -->
      <el-card class="time">
        <div slot="header" class="clearfix">
          <span>剩余时间</span>
        </div>
        <div class="body">
          <span v-if="type != 'readonly'"
          >{{ this.date.h >= 10 ? this.date.h : '0' + this.date.h }}:
            {{ this.date.m >= 10 ? this.date.m : '0' + this.date.m }}:
            {{ this.date.s >= 10 ? this.date.s : '0' + this.date.s }}
          </span>
          <span v-else>-- : -- : --</span>
        </div>
      </el-card>

      <!-- 交卷按钮 -->
      <el-button type="primary" class="submit" @click="finish" v-show="type != 'readonly'">交卷</el-button>

      <!-- 卷子主体 -->
      <el-card class="problem-list">
        <ul>
          <div v-for="(pName, ind) in Object.keys(afterProblem)" :key="ind">
            <h3 v-if="afterProblem[pName].length > 0">
              {{ zhNumberArray[ind] }}、{{ pName }}
            </h3>
            <template v-if="pName == '选择题'">
              <choice
                v-for="(item, index) in afterProblem['选择题']"
                :key="index + ' ' + ind"
                :data="item"
                :num="index + 1"
                :last-answer="answer[zhToEnMap[pName]][index]"
                ref="选择题"
              ></choice>
            </template>
            <template v-else-if="pName == '多选题'">
              <multiple-choice
                v-for="(item, index) in afterProblem['多选题']"
                :key="index + ' ' + ind"
                :data="item"
                :last-answer="answer[zhToEnMap[pName]][index]"
                ref="多选题"
                :num="index + 1"
              ></multiple-choice>
            </template>
            <template v-else-if="pName == '填空题'">
              <cloze
                v-for="(item, index) in afterProblem['填空题']"
                :key="index + ' ' + ind"
                :data="item"
                :last-answer="answer[zhToEnMap[pName]][index]"
                :num="index + 1"
                ref="填空题"
              ></cloze>
            </template>
            <template v-else-if="pName == '判断题'">
              <judge
                v-for="(item, index) in afterProblem['判断题']"
                :key="index + ' ' + ind"
                :data="item"
                :last-answer="answer[zhToEnMap[pName]][index]"
                :num="index + 1"
                ref="判断题"
              ></judge>
            </template>
          </div>
        </ul>
      </el-card>
    </el-main>
  </el-container>
</template>


<script>
  import Choice from '../problem/Choice.vue'
  import Cloze from '../problem/Cloze.vue'
  import Judge from '../problem/Judge.vue'
  import MultipleChoice from '../problem/MultipleChoice.vue'
  import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'

  export default {
    components: {
      Choice,
      Cloze,
      MultipleChoice,
      Judge
    },
    data () {
      return {
        loading: false,
        zhNumberArray: ['一', '二', '三', '四', '五', '六'],
        date: {
          h: 0,
          m: 0,
          s: 0,
        },
        zhToEnMap: {
          '选择题': 'choice',
          '多选题': 'multipleChoice',
          '判断题': 'judge',
          '填空题': 'cloze',
        },

        // 原始题目
        problems: {},
        // 题目数据进行适配
        afterProblem: {
          '选择题':[],
          '多选题':[],
          '判断题':[],
          '填空题':[],
        },
        // 题目顺序集合
        problemArray:[

        ],
        readAnswer:[],
        score:0,
        totalScore: 0,
        type: this.$route.query.type,
      }
    },
    computed: {
      ...mapGetters([
        // 试卷信息
        'examInfo',
        'answer',
        'problemsInfo',
        'userInfo',
      ]),

    },
    async created () {
      this.$store.commit('editExamSubmit', false)
      await this.getProblems()
      if (this.type == 'readonly') {
      } else {
        // 开始倒计时
        this.countDown()
      }
      // 初始化并解析数据
      this.initExam();

    },
    methods: {
      // 获取试卷
      async getProblems () {
        this.loading = true
        const temp = {
          userId: this.userInfo.id,
          examId: this.$route.query.id,
        }
        const { data: res } = await this.$http.get('exam', {
          params: temp,
        })
        if (res.code == 200) {
          return
        }
        this.problems = res.data.exam.examItemList;
        this.readAnswer = res.data.answers;
        this.totalScore = res.data.exam.totalScore;
        this.$store.commit('saveProblems', this.problems)
        this.$store.commit('editExamTime',res.data.exam.duration);
        this.$store.commit('editExamInfo',res.data.exam);
        this.loading = false
      },
      initExam() {
        for (let i = 0; i < this.problems.length; i++) {
          let element = this.problems[i];
          for (let j = 0; j < element.problemList.length; j++) {
            let item = element.problemList[j];
            this.afterProblem[element.type].push(item);
            this.problemArray.push(item);
          }
        }
        for (let j = 0; j < this.readAnswer.length; j++) {
          this.score += this.readAnswer[j].score;
        }
        for (let i = 0; i < this.problemArray.length; i++) {
          let element = this.problemArray[i];
          for (let j = 0; j < this.readAnswer.length; j++) {
            if (element.id == this.readAnswer[i].problemId) {
              element.trueAnswer = this.readAnswer[i].trueAnswer;
              element.userAnswer = this.readAnswer[i].userAnswer;
              element.isCorrect = this.readAnswer[i].isCorrect;
              element.score = this.readAnswer[i].score;
              break;
            }
          }
        }
      },
      // 交卷
      async finish () {

        if (this.examInfo.isSubmit) {
          return ;
        }
        this.loading = true;
        this.$store.commit('editExamSubmit', true)
        // 补全数组长度
        for (let key of Object.keys(this.afterProblem)) {
          if (this.answer[this.zhToEnMap[key]].length < this.afterProblem[key].length) {
            let str = this.zhToEnMap[key];
            let newStr = str.charAt(0).toUpperCase() + str.slice(1);
            const temp = {
              index: this.afterProblem[key].length - 1,
              data: null,
            }
            this.$store.commit("saveAnswer" + newStr, temp);
          }
        }
        const temp = {
          examId: this.$route.query.id,
          userId: this.userInfo.id,
          ...this.answer,
        }
        const { data: res } = await this.$http.post('exam/commit', temp).finally(() => {
          this.loading = false;
        });
        if (res.code == 200) {
          this.$message.error(res.data.msg);
        } else {
          this.$message.success('提交成功');
        }
        this.$router.push('/home/myExam')
        // 删除vuex里的考试信息
        this.$store.commit('removeAllAnswer')
      },
      // 倒计时
      countDown () {
        this.date.h = Math.floor(this.examInfo.time / 3600)
        this.date.m = Math.floor((this.examInfo.time % 3600) / 60)
        this.date.s = (this.examInfo.time % 3600) % 60
        setInterval(() => {
          // TODO 修改vuex时间
          this.$store.commit("editExamTime", this.examInfo.time - 1);
          if (this.date.s != 0) {
            this.date.s--
          } else {
            if (this.date.m != 0) {
              this.date.m--
              this.date.s = 59
            } else {
              if (this.date.h != 0) {
                this.date.h--
                this.date.m = 59
                this.date.s = 59
              } else {
                // 时间结束，自动交卷
                this.finish()
              }
            }
          }
        }, 1000)
      },
      // 退出考试
      exit () {
        if (this.type == 'readonly') {
          return this.$router.push('/home/myExam')
        }
        this.$confirm('退出考试将无法再次进入，你确定退出本次考试吗', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        })
          .then(() => {
            this.finish()
          })
          .catch(() => {
          })
      },
      // 答题卡题目状态
      problemState(item, index) {
        const en = this.zhToEnMap[item];
        if (this.type != 'readonly') {
          if (this.answer[en] == undefined ||
            this.answer[en][index - 1] == undefined) {
            return ''
          } else {
            let element = this.answer[en][index - 1]
            if (element == null || element == '') {
              return ''
            }
            const pattern = new RegExp('^#{1,100}$', 'i')
            const res = pattern.test(element)
            if (res) {
              return ''
            } else {
              return 'primary'
            }
          }
        } else {
          const element = this.afterProblem[item][index - 1];
          if (element.trueAnswer == element.userAnswer) {
            return 'success';
          }
          return 'danger'
        }
      },
      // 操作滚动条，切换至对应的题
      roll (type, index) {
        this.$refs.problemsBody.$el.scrollTop =
          this.$refs[type][index - 1].$el.offsetTop - 100
      },
    },
  }
</script>

<style lang="scss">
  .exam {
    margin: 0 auto;
    height: 100%;

    .el-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 150px;
      border-bottom: 1px solid #f3f3f3;
    }

    .el-main {
      background-color: #eff3f7;
      position: relative;

      .answer-sheet {
        position: fixed;
        left: 4%;
        width: 290px;
        height: 600px;
        overflow-y: scroll;
        span {
          font-weight: 700;
        }

        .body {
          p {
            font-size: 14px;
            font-weight: 500;
            margin: 7px 0;
          }

          .el-button {
            margin-bottom: 4px;
            width: 40px;
          }

          .isFirst {
            margin-left: 0px;
          }
        }
      }

      .problem-list {
        width: 800px;
        margin: 0 auto;
        min-height: 500px;
        margin-left: 380px;

        ul {
          padding-left: 15px;
        }

        ul li {
          list-style: none;

          .title {
            span {
              margin-right: 10px;
              color: #63b1fe;
            }
          }

          p {
            padding-left: 15px;
            padding-right: 15px;
          }
        }
      }

      .time {
        position: fixed;
        right: 8%;
        width: 140px;
        text-align: center;

        .body {
          color: red;
        }
      }

      .submit {
        position: fixed;
        bottom: 10%;
        right: 8%;
        width: 140px;
      }
    }
  }
</style>
